import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const request = axios.create({
  // baseURL: '/api',
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000
})
request.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  // 请求失败
  error => {
    return Promise.reject(error)
  }
)
request.interceptors.response.use(
  response => {
    // 判断是不是Blob
    if (response.data instanceof Blob) return response.data // 返回了Blob对象
    const { data, message, success } = response.data
    if (success) {
      return data
    } else {
      Message.error({
        message
      })
      return Promise.reject(new Error(message))
    }
  },
  async error => {
    // 解决token过期问题
    if (error.response.status === 401) {
      Message.info({
        message: '登录过期，请重新登录'
      })
      // 退出登录，清除用户缓存信息
      await store.dispatch('user/logout')
      // 等待数据清理完成，跳转至登录页
      router.push('/login')
      return Promise.reject(error)
    }
    Message.error({
      message: error.response.data.message
    })
    return Promise.reject(error)
  }
)
export default request
